// console.log(jQuery, $)
let listArray = [
  {url: 'https://www.bilibili.com',name:'https://www.bilibili.com'},
  {url: 'https://xiedaimala.com',name:'https://xiedaimala.com'}
];
const sessionList = localStorage.getItem('menu');
if (sessionList) {
  // console.log()
  listArray = JSON.parse(sessionList);
}

const formatUrlName = (name,flag) => {
  const myName= name.replace('https://', '').replace('www.', '')
  // console.log(arguments, name)
  if (flag) {
    return myName;
  } else {
    return myName[0] ? myName[0].toUpperCase() :''
  }
}

const $siteList = $('.siteList')
const $lastLi = $('.last')

const updateList = () => {
  $siteList.find('li:not(.last)').remove()
  listArray.forEach((card, index) => {
    // console.log(card, 11)
    const $li = $(`<li data-x=${card.url}>
    <div class="site">
      <div class="logo">${formatUrlName(card.name)}</div>
      <div class="link">${formatUrlName(card.url, 'url')}</div>
      <div class="close">
        <div class="icon">
        X
        </div>
      </div>
    </div>
  </li>`).insertBefore($lastLi)
    $li.on('click', () => {
      console.log('我点击了', card)
      window.open(card.url)
    })
    $li.on('click', ' .close', (e)=>{
      e.stopPropagation();
      listArray.splice(index, 1);
      updateList()
    })
  })
}

updateList();

$('.last').on('click', () => {
  console.log('点击了加号')
  let url = window.prompt('请问你要添加的网址是？')
  if (!url.includes('http')) {
    url = 'https://' + url;
  }
  console.log(url, 123)
  listArray.push({
    url: url,
    name: formatUrlName(url),
  })
  updateList();
})

console.log(listArray, 334)
$('button').on('click', (e) => {
  const searchInput = $('input#search')
  // console.log(e, searchInput.val())
  window.open('https://www.baidu.com/s?wd='+searchInput.val())
})
window.onbeforeunload = () => {
  const string = JSON.stringify(listArray)
  localStorage.setItem('menu', string)
}